package controller

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/response"
	"gitee.com/song-yao-shun/MQH/util"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
	"log"
	"net/http"
)

func Register(c *gin.Context) {
	////获取参数
	//name := c.PostForm("name")
	//telephone := c.PostForm("telephone")
	//password := c.PostForm("password")

	////使用 map 获取请求的参数
	//var requestMap = make(map[string]string)
	//json.NewDecoder(c.Request.Body).Decode(&requestMap)

	// 使用 结构体 获取请求的参数
	var requestUser = model.User{}
	//json.NewDecoder(c.Request.Body).Decode(&requestUser)
	c.Bind(&requestUser)

	name := requestUser.Name
	telephone := requestUser.Telephone
	password := requestUser.Password

	//数据验证
	if len(telephone) != 11{
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11为")
		return
	}
	if len(password) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码长度必须大于6")
		return
	}
	// 业务逻辑验证：如果name没有传，给一个10位的随机数
	if len(name) == 0{
		name = util.RandomString(10)
	}
	// 业务逻辑验证：判断手机号是否存在
	DB := common.GetDB()
	if getUserByTelephone(DB, telephone) != (model.User{}){
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户已存在")
		return
	}

	// 行为：创建用户
	cryptpw, err := bcrypt.GenerateFromPassword([]byte(password),bcrypt.DefaultCost)
	if err != nil{
		response.Response(c, http.StatusInternalServerError, 500, nil, "加密异常")
		return
	}
	NewUser := model.User{
		Name:		name,
		Telephone: 	telephone,
		Password: 	string(cryptpw),
	}
	DB.Create(&NewUser)

	//行为
	token, err := common.ReleaseToken(NewUser)
	if err != nil{
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统异常")
		log.Printf("token generate token: %v",err)
		return
	}

	//返回结果
	response.Success(c, gin.H{"token":token}, "登录成功")
}

func Login(c *gin.Context){
	// 使用 结构体 获取请求的参数
	var requestUser = model.User{}
	c.Bind(&requestUser)

	telephone := requestUser.Telephone
	password := requestUser.Password

	//数据验证
	if len(telephone) != 11{
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11为")
		return
	}
	if len(password) < 6 {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "密码长度必须大于6")
		return
	}
	//业务逻辑验证:手机号是否存在
	DB := common.GetDB()
	user := getUserByTelephone(DB, telephone)
	if user == (model.User{}) {
		response.Response(c, http.StatusUnprocessableEntity, 422, nil, "用户不存在")
		return
	}
	//业务逻辑验证：密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password),[]byte(password));err!=nil{
		response.Fail(c, nil, "密码错误")
		return
	}

	//行为
	token, err := common.ReleaseToken(user)
	if err != nil{
		response.Response(c, http.StatusInternalServerError, 500, nil, "系统异常")
		log.Printf("token generate token: %v",err)
		return
	}

	//返回结果
	response.Success(c, gin.H{"token":token}, "登录成功")
}

func UserInfo(c *gin.Context){
	user, _ := c.Get("user")
	response.Success(c, gin.H{"user":dto.ToUserDto(user.(model.User))}, "")
}

func getUserByTelephone(db *gorm.DB, telephone string) model.User{
	var user model.User
	db.Where("telephone = ?",telephone).First(&user)
	return user
}


